<template>
  <el-dialog
    v-model="show" destroy-on-close :title="title" width="1000px" append-to-body
    :close-on-click-modal="false" @close="delWatch"
  >
    <el-form
      ref="ruleFormRef"
      label-position="top" label-width="120px" class="chooseForm" :model="form"
      :rules="rules"
    >
      <el-row class="athletesform">
        <el-col v-show="signType!=0" :span="8" style="max-height: 70vh;overflow: auto;">
          <el-form-item label="可报运动员" class="athletes">
            <el-radio-group v-model="form.manId" class="ml-4">
              <div v-for="item in athletesList" :key="item.id" :ref="item.id" class="mb20">
                <el-radio-button :label="item.id" size="large" @change="changePersonal(item)">
                  <div class="optionFlex">
                    <el-avatar v-show="item.picUrl" :size="40" :src="item.picUrl" />
                    <p class="name">{{ item.realName }}
                      <span v-show="item.sex=='0'">(女)</span>
                      <span v-show="item.sex=='1'">(男)</span>
                    </p>
                  </div>
                </el-radio-button>
                <el-button
                  v-if="noPhotoCanSign=='0'&&(!item.picUrl)" class="ml20" type="text"
                  @click="editPersonInfo(item.id,nowMan.groupId)"
                >上传照片
                </el-button>
              </div>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-loading="loading" :span="16" style="max-height: 70vh;overflow: auto;">
          <el-empty v-show="treeData.length<1" description="请选择运动员" />
          <el-collapse v-for="(project,index) in treeData" :key="project.id" v-model="activeNames">
            <div v-show="project.hasNext==0&&project.canSign=='1'" class="fake-collapse-item">
              <el-checkbox-group v-model="form.levelId" size="large">
                <el-checkbox :label="project.levelId">{{ project.name }}</el-checkbox>
              </el-checkbox-group>
            </div>
            <el-collapse-item v-show="project.hasNext==1&&project.canSign=='1'" :title="project.name" :name="index">
              <div v-for="group in project.groupList" :key="group.id">
                <div v-show="group.hasNext==0">
                  <el-checkbox-group v-model="form.levelId" size="large">
                    <el-checkbox v-show="group.canSign=='1'" :label="group.levelId">{{ group.name }}</el-checkbox>
                    <!--                    <el-checkbox v-show="group.hasNext!=0" disabled :label="group.id">{{ group.name }}</el-checkbox>-->
                  </el-checkbox-group>
                </div>

                <div v-show="group.hasNext==1">
                  <el-checkbox-group
                    v-for="level in group.levelList" :key="level.id" v-model="form.levelId"
                    size="large"
                  >
                    <!-- project.type判断选队友  signId删除报项 :disabled="level.canSign==0||level.belongToThisTeam==0"-->
                    <el-checkbox v-show="level.canSign==1" :label="level.id" :checked="level.checked">
                      {{ group.name }}{{ level.name }}
                      <span v-show="level.levelType=='1'">(男)</span>
                      <span v-show="level.levelType=='2'">（女）</span>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog v-model="showMateList" :title="mateTitle" width="900px" draggable @close="mateClose">
      <div class="mb20">
        <span v-if="mateConfig.minCount!=mateConfig.maxCount">请选择{{ mateConfig.minCount }}~{{
          mateConfig.maxCount
        }}个队友</span>
        <span v-else-if="mateConfig.minCount=='-1'&&mateConfig.maxCount=='-1'">请至少选择1个队友</span>
        <span v-else>请选择{{ mateConfig.minCount }}个队友</span>

        <span v-if="mateConfig.minMaleCount>0||mateConfig.maxMaleCount>0" style="margin:0 20px;">男子:
          <span v-show="mateConfig.minMaleCount!=mateConfig.maxMaleCount&&mateConfig.minMaleCount!=-1"> 最少{{ mateConfig.minMaleCount }}人 </span>
          <span v-show="mateConfig.minMaleCount!=mateConfig.maxMaleCount&&mateConfig.maxMaleCount!=-1"> 最多{{ mateConfig.maxMaleCount }}人</span>
          <span v-show="mateConfig.minMaleCount==mateConfig.maxMaleCount&&mateConfig.maxMaleCount!=-1">{{ mateConfig.maxMaleCount }}人</span>
        </span>
        <span v-if="mateConfig.minFemaleCount>0||mateConfig.maxFemaleCount>0" style="margin:0 20px;">女子:
          <span v-show="mateConfig.minFemaleCount!=mateConfig.maxFemaleCount&&mateConfig.minFemaleCount>0"> 最少{{ mateConfig.minFemaleCount }}人 </span>
          <span v-show="mateConfig.minFemaleCount!=mateConfig.maxFemaleCount&&mateConfig.maxFemaleCount>0"> 最多{{ mateConfig.maxFemaleCount }}人</span>
          <span v-show="mateConfig.minFemaleCount==mateConfig.maxFemaleCount&&mateConfig.minFemaleCount>0">{{ mateConfig.minFemaleCount }}人</span>
        </span>

        <span v-show="form.mates.length>1" style="float: right" class="text-success">已选{{ form.mates.length-1 }}个队友</span>
      </div>
      <!--      <el-button v-if="teammateList.length<minCount" type="text" @click="addTeamMate">新增队友</el-button>-->
      <el-empty v-if="teammateList.length==0" description="暂无可选队友" />
      <div class="teammateList" style="max-height:60vh;overflow: auto;">
        <el-checkbox-group v-model="form.mates" class="ml-4" @change="changeTeammates">
          <el-checkbox disabled checked :label="personal.sex+'_'+personal.id" size="large">
            <div class="optionFlex" style="width: auto;">
              <div style="width: 40px;"><img v-show="personal.picUrl" :src="personal.picUrl" width="40"></div>
              <p class="name" style="width: 200px">{{ personal.realName }}
                <span v-show="personal.sex=='0'">(女)</span>
                <span v-show="personal.sex=='1'">(男)</span>
              </p>
              <el-select v-show="sonLevelList.length>0" v-model="personal.sonlevel" clearable>
                <el-option v-for="son in sonLevelList" :value="son.id" :label="son.name">{{ son.name }}</el-option>
              </el-select>
            </div>
          </el-checkbox>

          <div v-for="(item,index) in teammateList" :key="item.id" class="mb20">
            <el-checkbox :label="item.sex+'_'+item.id" size="large" :disabled="item.disabled">
              <div class="optionFlex" style="width: auto;">
                <span>{{ index+1 }}、</span>
                <div style="width: 40px;"><img v-show="item.picUrl" :src="item.picUrl" width="40"></div>
                <p class="name" style="width: 200px">{{ item.realName }}
                  <span v-if="item.sex=='0'">(女)</span>
                  <span v-else>(男)</span>
                </p>
                <el-select v-show="sonLevelList.length>0" v-model="item.sonlevel" clearable>
                  <el-option v-for="son in sonLevelList" :value="son.id" :label="son.name">{{ son.name }}</el-option>
                </el-select>
              </div>
            </el-checkbox>
            <el-button v-if="noPhotoCanSign=='0'&&(!item.picUrl)" class="ml20" type="text" @click="editPersonInfo(item.id,nowMan.groupId)">
              上传照片
            </el-button>
          </div>
        </el-checkbox-group>
      </div>

      <el-transfer v-model="form.mates" :data="teammateList" :titles="['可选队友','已选队友']"
                   @left-check-change="changeTeammates" @change="transferChange">
        <template #default="scope">
          <div class="transferItem">
            <img v-show="scope.option.picUrl" :src="scope.option.picUrl" width="50" height="70">
            <div class="name">
              {{ scope.option.realName }}
              <span v-if="scope.option.sex=='0'">女</span>
              <span v-else>男</span>
            </div>
            <el-select v-show="sonLevelList.length>0" v-model="scope.option.sonlevel" clearable>
              <el-option v-for="son in sonLevelList" :key="son.id" :value="son.id" :label="son.name">{{ son.name }}</el-option>
            </el-select>
          </div>
        </template>
      </el-transfer>

      <template #footer>
        <div class="dialog-footer text-center">
          <el-button type="primary" @click="chooseMateDone">确定</el-button>
        </div>
      </template>

    </el-dialog>


    <dialogPersonInfo ref="editPersonInfoRef" @submitForm="getAthletesList" />

  </el-dialog>
</template>

<script setup>
import { reactive, ref, toRefs, watch } from 'vue'
import { getCurrentInstance, nextTick, onMounted } from '@vue/runtime-core'
import * as match from '@/api/match/pc'
import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance()
const emit = defineEmits(['submitForm'])
import dialogPersonInfo from '../components/addCoach'
import _ from 'lodash'

const data = reactive({
  show: false,
  title: '', mateTitle: '',
  signType: '',
  form: {
    levelId: [],
    mates: []
  },
  athletesList: [],
  signProjectList: [],
  signGroupList: [],
  showMateList: false,
  showBtn: false,
  teammateList: [],
  rankId: '0',
  treeData: [],
  loading: false,
  mateConfig: {},
  noPhotoCanSign: null,
  coachOrLeaderFlag: null,
  personal: {},
  activeNames: [0],
  okMates: []
})
const {
  signType,
  form,
  rules,
  loading,
  activeNames,
  athletesList,
  treeData,
  show,
  title, mateTitle,
  personal,
  rankId,
  showMateList,
  showBtn,
  teammateList,
  mateConfig,
  noPhotoCanSign,
  coachOrLeaderFlag,
  okMates
} = toRefs(data)
let matchId
let groupId
watch(show, (val) => {
  if (!val) {
    form.value = {}
    treeData.value = []
    delWatch()
  }
})
const changePersonal = (item) => {
  // delWatch()
  personal.value = item
  form.value.manId = item.id
  getTree()
}

function getTree() {
  noLevelId = ''
  loading.value = true
  match.getMySignListTree(matchId, form.value.manId, rankId.value).then(res => {
    treeData.value = res.data
    // 循环项目，组，级别 赋值是否checked
    getMyIsSign()
  })
}

let signOk = {}

function getMyIsSign() {
  delWatch()
  form.value.levelId = []
  match.getMySignIds(matchId, form.value.manId, rankId.value).then(res => {
    loading.value = false
    signOk = res.data
    for (const s of signOk) {
      form.value.levelId.push(s.eid)
      for (const p of treeData.value) {
        if (p.levelId == s.eid) {
          p.checked = true
          p.signId = s.signId
          p.belongToThisTeam = s.belongToThisTeam
        } else {
          for (const g of p.groupList) {
            g.type = p.type
            if (g.levelId == s.eid) {
              g.checked = true
              g.signId = s.signId
              g.belongToThisTeam = s.belongToThisTeam
            } else {
              for (const l of g.levelList) {
                l.type = p.type
                if (s.eid == l.id) {
                  l.checked = true
                  l.signId = s.signId
                  l.belongToThisTeam = s.belongToThisTeam
                }
              }
            }
          }
        }
      }
    }
    if (signOk.length < 1) {
      for (const p of treeData.value) {
        for (const g of p.groupList) {
          g.type = p.type
          for (const l of g.levelList) {
            l.type = p.type
          }
        }
      }
    }
    addWatch()
  })
}

//#region 监听叶子的数量变化
let noLevelId
let levelInfo
let watchHandle = null

function addWatch() {
  delWatch()
  watchHandle = watch(() => form.value.levelId, (newValue, oldValue) => {
    if (!newValue) return
    oldValue = _.uniq(oldValue)
    newValue = _.uniq(newValue)
    // console.log(newValue, oldValue)
    let temp
    let isAdd = false
    if (newValue?.length > oldValue?.length) {
      isAdd = true
      temp = _.difference(newValue, oldValue)
    } else {
      isAdd = false
      temp = _.difference(oldValue, newValue)
    }
    if (newValue[0] == temp[0]) {

    }
    if (temp.length === 1) {
      levelInfo = findlevelInfo(temp[0], treeData.value, 1)
      if (isAdd) {
        noLevelId = temp[0]
        judgeChooseTeam(levelInfo.type, temp[0])
      } else {
        if (!temp[0] || temp[0] == undefined) {
          return
        }
        removeThis(levelInfo.signId)
      }
    }
    // console.log(isAdd, temp[0])
  })
}

function delWatch() {
  if (watchHandle) {
    watchHandle()
    watchHandle = null
  }
}

function findlevelInfo(id, list, deep) {
  let info = null
  _.some(list, (l) => {
    switch (deep) {
      case 1:// p
        if (l.levelId == id) {
          info = l
        } else {
          info = findlevelInfo(id, l.groupList, 2)
        }
        break
      case 2:// g
        if (l.levelId == id) {
          info = l
        } else {
          info = findlevelInfo(id, l.levelList, 3)
        }
        break
      case 3:// l
        if (l.id == id) {
          info = l
        }
        break
    }
    return info
  })

  return info
}

//#endregion
function getAthletesList() {
  match.getMyGroupForCpt(groupId, matchId).then(res => {
    athletesList.value = res.data.athletes
    if (form.value.manId) {
      for (const a of athletesList.value) {
        if (a.id == form.value.manId) {
          nowMan.value = a
        }
      }
    }
  })
}

const open = (params) => {
  show.value = true
  matchId = params.matchId
  groupId = params.groupId
  signType.value = params.signType
  title.value = params.title
  rankId.value = params.rankId || ''
  noPhotoCanSign.value = params.noPhotoCanSign
  coachOrLeaderFlag.value = params.coachOrLeaderFlag
  if (params.personal) {
    form.value.manId = params.personal.id
    setTimeout(() => {
      proxy.$refs[params.personal.id][0].scrollIntoView({ block: 'start', behavior: 'smooth' })
    }, 200)

    getTree()
    personal.value = params.personal
  }
  if (groupId != 0) {
    if (params.choosedList) {
      athletesList.value = params.choosedList
      if (form.value.manId) {
        for (const a of athletesList.value) {
          if (a.id == form.value.manId) {
            nowMan.value = a
          }
        }
      }
    } else {
      getAthletesList()
    }
  }
}
defineExpose({
  open
})

const nowMan = ref({})
const sonLevelList = ref([])
let sonLevelIds = []

function editPersonInfo(id, groupId) {
  const params = {
    id: id,
    groupId: groupId
  }
  proxy.$refs['editPersonInfoRef'].open(params)
}

function addTeamMate() {
  const params = {
    id: 0,
    groupId: groupId
  }
  proxy.$refs['editPersonInfoRef'].open(params)
}
function transferChange(value, direction, movedKeys) {
  console.log(value, direction, movedKeys)
  console.log(form.value.mates)
}
const judgeChooseTeam = (type, levelId) => {
  const tmArr = ['1', '2', '3', '4', '6']
  if (tmArr.indexOf(type) > -1) {
    getTeammate(levelId)
  } else {
    const obj = {
      levelId: levelId,
      athleteIds: form.value.manId,
      groupId: groupId,
      teamId: rankId.value || ''
    }
    saveOne(obj)
  }
}
const getTeammate = (levelId) => {
  const obj = {
    levelId: levelId,
    groupId: groupId,
    personId: form.value.manId
  }
  match.getCanSignLevelPerson(obj).then(res => {
    mateConfig.value = res.data
    teammateList.value = res.data.personList
    for (const p of teammateList.value) {
      p.disabled = false
      if (mateConfig.value.maxMaleCount == 0 && p.sex == '1') {
        p.disabled = true
      }
      if (mateConfig.value.maxFemaleCount == 0 && p.sex == '0') {
        p.disabled = true
      }
      p.key = `${p.sex}_${p.id}`
      p.label = `${p.realName}(${p.sexStr})`
    }
    getSonLevels(levelId)
    mateTitle.value = `选择队友 (${teammateList.value.length})`
    showMateList.value = true
    form.value.mates = []
    sonLevelIds = []
    personal.value.sonlevel = ''
  }).catch(error => {
    getMyIsSign()
  })
}

function getSonLevels(level) {
  sonLevelList.value = []
  match.querySonLevel(level).then(res => {
    sonLevelList.value = res.data
  })
}

let manNum = 0
let femaleNum = 0
let mates = []
const changeTeammates = (e) => {
  mates = []
  manNum = 0
  femaleNum = 0
  for (const m of e) {
    const arr = m.split('_')
    mates.push(arr[1])
    if (personal.value.id == arr[1]) {
      continue
    }
    if (arr[0] == '1') {
      manNum++
    } else {
      femaleNum++
    }
  }
  // console.log(mates, mateConfig.value)
  for (const p of teammateList.value) {
    if (mateConfig.value.maxMaleCount != -1 && manNum == mateConfig.value.maxMaleCount && p.sex == '1' && mates.indexOf(p.id) == -1) {
      p.disabled = true
    } else if (mateConfig.value.maxFemaleCount != -1 && femaleNum == mateConfig.value.maxFemaleCount && p.sex == '0' && mates.indexOf(p.id) == -1) {
      p.disabled = true
    } else if (mates.indexOf(p.id) == -1 && mateConfig.value.maxCount != -1 && (mates.length - 1) == mateConfig.value.maxCount) {
      p.disabled = true
    } else {
      p.disabled = false
    }
  }
}
const mateClose = () => {
  mates = []
  form.value.mates = []
  sonLevelIds = []
  teammateList.value = []
  getMyIsSign()
}

function chooseMateDone() {
  if (mateConfig.value.minMaleCount != '-1' && mateConfig.value.minMaleCount != '0' && manNum < mateConfig.value.minMaleCount) {
    ElMessage.error(`至少选择${mateConfig.value.minMaleCount}个男队友`)
    return
  }
  if (mateConfig.value.maxMaleCount != '-1' && mateConfig.value.maxMaleCount != '0' && manNum > mateConfig.value.maxMaleCount) {
    ElMessage.error(`最多选择${mateConfig.value.maxMaleCount}个男队友`)
    return
  }
  if (mateConfig.value.minFemaleCount != '-1' && mateConfig.value.minFemaleCount != '0' && femaleNum < mateConfig.value.minFemaleCount) {
    ElMessage.error(`至少选择${mateConfig.value.minFemaleCount}个女队友`)
    return
  }
  if (mateConfig.value.maxFemaleCount != '-1' && mateConfig.value.maxFemaleCount != '0' && femaleNum > mateConfig.value.maxFemaleCount) {
    ElMessage.error(`最多选择${mateConfig.value.maxFemaleCount}个女队友`)
    return
  }
  if ((mates.length < mateConfig.value.minCount) && mateConfig.value.minCount > 0) {
    ElMessage.error(`至少选择${mateConfig.value.minCount}个队友`)
    return
  }
  const athleteIds = []
  console.log('mates', mates)
  for (const p of teammateList.value) {
    if (mates.indexOf(p.id) != -1) {
      if (sonLevelList.value.length > 0 && !p.sonlevel) {
        ElMessage.error(`请分配级别`)
        return
      }
      sonLevelIds.push(p.sonlevel)
      athleteIds.push(p.id)
    }
  }
  if (sonLevelList.value.length > 0 && !personal.value.sonlevel) {
    ElMessage.error(`请分配级别`)
    return
  }
  sonLevelIds.push(personal.value.sonlevel)
  athleteIds.push(personal.value.id)
  if (sonLevelList.value.length == 0) {
    sonLevelIds = []
  }
  const obj = {
    levelId: noLevelId,
    athleteIds: athleteIds.toString(),
    sonLevelIds: sonLevelIds.toString() || '',
    groupId: groupId,
    teamId: rankId.value || ''
  }
  // 半提交
  saveOne(obj)
}


const saveOne = (obj) => {
  loading.value = true
  match.sportsmanDone(obj).then(res => {
    if (res.msg.indexOf('Exception:') > -1) {
      const msg = res.msg.slice(10)
      ElMessage({
        type: 'warning',
        message: msg
      })
      // form.value.mates = []
      sonLevelIds = []
      getMyIsSign()
      return
    }
    sonLevelIds = []
    // form.value.mates = []
    showMateList.value = false
    sonLevelList.value = []
    getMyIsSign()
    emit('submitForm')
  }).catch(err => {
    // 取消这个勾
    getMyIsSign()
    sonLevelIds = []
  })
}

function removeThis(id) {
  loading.value = true
  match.deleteSign(id).then(res => {
    // 重新获取已报名信息
    loading.value = false
    emit('submitForm')
  }).catch(err => {
    getMyIsSign()
  })
}
</script>

<style lang="scss" scoped>
.el-transfer{
  --el-transfer-item-height: 70px;
  --el-transfer-panel-width: 320px;
}
.transferItem{display: flex;align-items: center;
  img{margin-right: 6px;}
  .name{line-height: 1.6;font-size: 15px;
    span{display: block;color: #999;font-size: 14px}
  }
}
.optiontitle {
  font-size: 14px;
  padding: 0 10px;
  line-height: 1;
  margin: 10px 0;
  border-left: 2px solid #1ab394;
}

.optionFlex {
  display: flex;
  align-items: center;
  padding: 10px 0;
  width: 200px;

  .name {
    margin: 0 20px;
    font-size: 16px;
  }
}

.el-radio-group {
  width: 100%;
  display: block;
}

.athleteBox {
  height: 80px;
  display: flex;
  align-items: center;

  :deep(.el-radio__label) {
    display: flex;
    align-items: center;
    margin: 0 20px;
  }

  .el-radio__inner {
    scale: 1.5;
  }

  .name {
    margin: 0 20px;
    font-size: 16px;
  }
}

.athleteBox:hover {
  background: #efefef;
}

.tip {
  font-size: 13px;
  color: #999;
  margin: 10px 0;

  i {
    color: red;
    margin: 0 4px 0 0;
  }
}

p.title {
  font-size: 16px;
  margin: 0 0 15px;
}

:deep(.el-collapse-item) {
  background: #FBFCFD;
  margin: 0 0 16px;
  padding: 0 15px;
}

:deep(.el-collapse-item__wrap) {
  background: #FBFCFD;
  border: none;
  padding: 0 10px;
}

:deep(.el-collapse) {
  border: none;
}

:deep(.el-collapse-item__header) {
  border: none;
  background: #ececec;
  padding: 0 0 0 10px;    font-size: 15px;
}

:deep(.el-collapse-item__content) {
  padding-bottom: 0;
}

:deep(.el-checkbox__input.is-disabled+span.el-checkbox__label) {
  color: #4C5359;
}

.fake-collapse-item {
  background: #FBFCFD;
  margin: 0 0 16px;
  padding: 0 15px;
}
:deep(.el-checkbox.el-checkbox--large .el-checkbox__label){
  font-size: 16px;
}
.teammateList :deep(.el-checkbox.el-checkbox--large) {
  height: auto;
}
</style>
